package com.siyoumi.app.modules.redbook.service;

import com.siyoumi.app.entity.RedbookComment;
import com.siyoumi.app.entity.RedbookQuan;
import com.siyoumi.app.entity.SysUser;
import com.siyoumi.app.modules.redbook.vo.RedbookCommentAuditVo;
import com.siyoumi.app.modules.redbook.vo.RedbookCommentVo;
import com.siyoumi.app.service.RedbookCommentService;
import com.siyoumi.component.XApp;
import com.siyoumi.component.XSpringContext;
import com.siyoumi.component.http.InputData;
import com.siyoumi.component.http.XHttpContext;
import com.siyoumi.exception.EnumSys;
import com.siyoumi.mybatispuls.JoinWrapperPlus;
import com.siyoumi.service.IWebService;
import com.siyoumi.util.XDate;
import com.siyoumi.util.XReturn;
import com.siyoumi.util.XStr;
import com.siyoumi.validator.XValidator;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.List;

//评论
@Slf4j
@Service
public class SvcRedbookComment
        implements IWebService {
    static public SvcRedbookComment getBean() {
        return XSpringContext.getBean(SvcRedbookComment.class);
    }

    static public RedbookCommentService getApp() {
        return RedbookCommentService.getBean();
    }


    /**
     * 获取评论数
     *
     * @param quanId
     * @param pid
     */
    public Long getCount(String quanId, String pid) {
        JoinWrapperPlus<RedbookComment> query = getCountQuery(quanId, pid);
        return getApp().count(query);
    }

    public JoinWrapperPlus<RedbookComment> getCountQuery(String quanId, String pid) {
        JoinWrapperPlus<RedbookComment> query = listQuery(quanId);
        query.eq("rbc_enable", 1);

        if (XStr.hasAnyText(pid)) {
            query.eq("rbc_pid", pid);
        }

        return query;
    }

    public JoinWrapperPlus<RedbookComment> listQuery(List<String> quanIdArr) {
        if (quanIdArr == null || quanIdArr.size() == 0) {
            XValidator.err(20081, "quanIdArr null or 0");
        }

        InputData inputData = InputData.getIns();
        JoinWrapperPlus<RedbookComment> query = listQuery(inputData);
        query.in("rbc_rquan_id", quanIdArr);

        return query;
    }

    public JoinWrapperPlus<RedbookComment> listQuery(String quanId) {
        return listQuery(Arrays.asList(quanId));
    }

    /**
     * 2级
     *
     * @param pidArr
     * @return
     */
    public JoinWrapperPlus<RedbookComment> selectQuery(List<String> pidArr) {
        InputData inputData = InputData.getIns();
        inputData.put("order_type", "null");
        JoinWrapperPlus<RedbookComment> query = selectQuery(inputData);
        query.in("rbc_pid", pidArr);
        return query;
    }

    public JoinWrapperPlus<RedbookComment> selectQuery(InputData inputData) {
        String[] select = {
                "user.user_id user_id",
                "user.user_name user_name",
                "user.user_headimg user_headimg",
                "reply.user_id reply_user_id",
                "reply.user_name reply_user_name",
                "reply.user_headimg reply_user_headimg",
                "rbc_id",
                "rbc_pid",
                "rbc_rquan_id",
                "rbc_is_master",
                "rbc_create_date",
                "rbc_content",
                "rbc_pic",
                "rbc_good_count",
                "rbc_enable",
                "rbc_reply_num",
        };
        JoinWrapperPlus<RedbookComment> query = listQuery(inputData);
        query.join(SysUser.table() + " AS user", "rbc_uid", "user.user_id");
        query.leftJoin(SysUser.table() + " AS reply", "rbc_reply_to", "reply.user_id"
                , " AND reply.user_x_id = {0}", XHttpContext.getX());
        query.select(select);
        query.eq("user.user_x_id", XHttpContext.getX());


        return query;
    }

    /**
     * select
     *
     * @return query
     */
    public JoinWrapperPlus<RedbookComment> listQuery(InputData inputData) {
        String quanId = inputData.input("quan_id");
        String createBegin = inputData.input("create_begin");
        String createEnd = inputData.input("create_end");
        String waitAudit = inputData.input("wait_audit");
        String type = inputData.input("type");
        String orderType = inputData.input("order_type");
        String pid = inputData.input("pid");
        String uid = inputData.input("uid");

        JoinWrapperPlus<RedbookComment> query = getApp().join();
        query.eq("rbc_x_id", XHttpContext.getX());

        if (XStr.hasAnyText(quanId)) { //小红书ID
            query.eq("rbc_rquan_id", quanId);
        }
        if (XStr.hasAnyText(uid)) { //用户ID
            query.eq("rbc_uid", uid);
        }
        if (XStr.hasAnyText(waitAudit)) {
            //审核状态
            if ("1".equals(waitAudit)) {
                //待审核
                query.and(q -> {
                    q.eq("rbc_enable", 0)
                            .or().eq("rbc_enable_reply", 1);
                });
            } else {
                //已审核
                query.ne("rbc_enable", 0);
            }
        }
        if (XStr.hasAnyText(createBegin) && XStr.hasAnyText(createEnd)) { //创建时间
            LocalDateTime b = XDate.parse(createBegin);
            LocalDateTime e = XDate.parse(createEnd);
            query.between("rbc_create_date", b, e);
        }
        //类型
        if (XStr.hasAnyText(type)) {
            switch (type) {
                case "0": //朋友圈
                    if (XStr.isNullOrEmpty(quanId)) {
                        XValidator.err(20154, "缺少朋友圈ID");
                    }

                    query.eq("rbc_rquan_id", quanId);
                    break;
                case "1": //用户
                    query.eq("rbc_uid", "");
                    break;
            }
        }
        //排序类型
        if (XStr.hasAnyText(orderType)) {
            switch (orderType) {
                case "0": //创建时间
                    query.orderByDesc("rbc_create_date")
                            .orderByAsc("id");
                    break;
                case "1": //点赞数
                    query.orderByDesc("rbc_good_count")
                            .orderByAsc("id");
                    break;
            }
        }
        if (XStr.hasAnyText(pid)) { //1级评论
            query.eq("rbc_pid", pid);
        }

        return query;
    }


    /**
     * 删除
     *
     * @return
     */
    @Transactional(propagation = Propagation.MANDATORY)
    public XReturn delete(List<String> ids) {
        getApp().delete(ids);
        return EnumSys.OK.getR();
    }


    /**
     * 审核通过
     *
     * @param enable
     */
    public XReturn enable(String commentId, Integer enable) {
        RedbookComment entityComment = getApp().getEntity(commentId);
        if (entityComment != null) {
            return EnumSys.ERR_VAL.getR("评论ID异常," + commentId);
        }

        return XApp.getTransaction().execute(transactionStatus -> {
            log.info("{}:更新审核状态", commentId);
            RedbookComment entityUpdate = new RedbookComment();
            entityUpdate.setRbc_id(entityComment.getRbc_id());
            entityUpdate.setRbc_enable(enable);
            entityUpdate.setRbc_enable_date(LocalDateTime.now());
            if (enable == 1) {
                if (XStr.hasAnyText(entityComment.getRbc_pid())) {
                    Long replyCount = getCount(entityComment.getRbc_rquan_id(), entityComment.getRbc_pid());
                    replyCount++;
                    entityUpdate.setRbc_reply_num(replyCount.intValue());
                }
            }
            getApp().saveOrUpdatePassEqualField(entityComment, entityUpdate);


            XReturn r = XReturn.getR(0);
            return r;
        });
    }

    /**
     * 标记2级评论存在待审核
     *
     * @param commentId
     */
    public void updateEnableReply(String commentId, Integer enable) {
        //RedbookComment entityUpdate = new RedbookComment();
        //entityUpdate.setRbc_id(commentId);
        //entityUpdate.setRbc_enable_reply(enable);
        //getApp().updateById(entityUpdate);
    }


    public boolean commentAutoEnable() {
        return true;
    }

    //能否评论
    public XReturn canCommentQuan(RedbookCommentVo vo) {
        return EnumSys.OK.getR();
    }

    public XReturn commentQuan(RedbookCommentVo vo) {
        RedbookQuan entityQuan = SvcRedbookQuan.getApp().getEntity(vo.getQuan_id());
        if (entityQuan == null) {
            return EnumSys.ERR_VAL.getR("quan_id异常");
        }

        XValidator.err(SvcRedbookQuan.getBean().validQuan(entityQuan));
        XReturn r = canCommentQuan(vo);
        if (r.err()) {
            return r;
        }

        if (XStr.hasAnyText(vo.getPid())) {
            RedbookComment entityComment = SvcRedbookComment.getApp().getEntity(vo.getPid());
            if (entityComment == null) {
                return XReturn.getR(20500, "评论ID异常");
            }
            if (XStr.hasAnyText(entityComment.getRbc_pid())) {
                return XReturn.getR(20515, "只能评论1级");
            }
            if (entityComment.getRbc_enable() != 1) {
                return XReturn.getR(20510, "评论未审核通过");
            }
        }

        RedbookComment entityComment = new RedbookComment();
        entityComment.setRbc_x_id(XHttpContext.getX());
        entityComment.setRbc_rquan_id(vo.getQuan_id());
        entityComment.setRbc_uid(getUid());
        entityComment.setRbc_content(vo.getContent());
        entityComment.setRbc_pic(vo.getPic());
        //一级ID
        entityComment.setRbc_pid(vo.getPid());
        if (XStr.hasAnyText(vo.getReply_to())) {
            //二级评论谁
            entityComment.setRbc_reply_to(vo.getReply_to());
        }
        if (entityQuan.getRquan_uid().equals(entityComment.getRbc_uid())) {
            //作者评论
            entityComment.setRbc_is_master(1);
        }
        entityComment.setAutoID();
        return XApp.getTransaction().execute(transactionStatus -> {
            getApp().save(entityComment);

            XReturn rr = XReturn.getR(0);
            if (commentAutoEnable()) {
                //自动审核通过
                RedbookCommentAuditVo commentAudit = new RedbookCommentAuditVo();
                commentAudit.setIds(Arrays.asList(entityComment.getRbc_id()));
                commentAudit.setEnable(1);
                audit(commentAudit);
            } else {
                //更新朋友圈待评论数
                //updateCommentCountCheck(entityQuan);
                if (XStr.hasAnyText(entityComment.getRbc_pid())) {
                    //标记2级评论存在待审核
                    SvcRedbookComment.getBean().updateEnableReply(entityComment.getRbc_id(), 1);
                }
            }


            rr.setData("is_good", false);
            rr.setData("entity", entityComment);
            return rr;
        });
    }


    public XReturn audit(RedbookCommentAuditVo vo) {
        List<Integer> enableArr = Arrays.asList(1, 10);
        if (!enableArr.contains(vo.getEnable())) {
            return EnumSys.ERR_VAL.getR("审核状态异常");
        }

        List<RedbookComment> listComment = SvcRedbookComment.getApp().get(vo.getIds());
        if (listComment.size() <= 0) {
            return EnumSys.ERR_VAL.getR("id异常");
        }

        return XApp.getTransaction().execute(transactionStatus -> {
            XReturn r = EnumSys.OK.getR();
            for (RedbookComment entityComment : listComment) {
                log.debug("{}:更新审核状态", entityComment.getRbc_id());
                RedbookComment entityUpdate = new RedbookComment();
                entityUpdate.setRbc_id(entityComment.getRbc_id());
                entityUpdate.setRbc_enable(vo.getEnable());
                entityUpdate.setRbc_enable_date(LocalDateTime.now());
                if (vo.getEnable() == 1) {
                    if (XStr.hasAnyText(entityComment.getRbc_pid())) {
                        Long replyCount = SvcRedbookComment.getBean().getCount(entityComment.getRbc_rquan_id(),
                                entityComment.getRbc_pid());
                        replyCount++;
                        entityUpdate.setRbc_reply_num(replyCount.intValue());
                    }
                }
                SvcRedbookComment.getApp().saveOrUpdatePassEqualField(entityComment, entityUpdate);

                RedbookQuan entityQuan = SvcRedbookQuan.getApp().getEntity(entityComment.getRbc_rquan_id());
                SvcRedbookQuan.getBean().updateCommentCount(entityQuan);
                SvcRedbookQuan.getBean().updateCommentLastIds(entityQuan);
            }

            return r;
        });
    }
}

